<?php

namespace IDock\Insurance\ZYIC\Response;

use IDock\Http\Response;
use IDock\IDock\IDockEnums;
use IDock\Insurance\ZYIC\ZYICEnums;
use IDock\Printer\NonCar\NonCarInquirySinglePrinter;
use IDock\Printer\Premium\PremiumBIPrinter;
use IDock\Printer\Premium\PremiumCoveragePrinter;
use IDock\Printer\Premium\PremiumInquiryPrinter;

class PremiumInquiryResponse extends AllZYICResponse
{

    public function resolve(): Response
    {
        $body = $this->getBody();
        if (!json_decode($body)) {
            $this->setError('返回数据异常');
            return $this;
        }
        $data = json_decode($body, true);

        if ($this->printer and is_string($this->printer)) {
            $this->printer = new $this->printer;
        }

        $resultCode = $data['code'] ?? '';
        $resultMess = $data['message'] ?? '';
        $errorMsg = $data['content']['errorMsg'] ?? '';

        $this->repeat($errorMsg);

        if ($this->printer->repeatInsuredFlg) {
            return $this;
        }

        if ($resultCode != '0000') {
            $this->setError($resultMess);
            return $this;
        }
        if (!empty($errorMsg)) {
            $this->setError($errorMsg);
            return $this;
        }
        $this->setBody($data);

        return $this;
    }

    /**
     * @var PremiumInquiryPrinter $printer
     * @var  $printer
     */
    public $printer = PremiumInquiryPrinter::class;


    public function printerInit(): Response
    {
        if (!$this->printer->success) {
            return $this;
        }
        $body = $this->getBody() ?? [];
        $msg = $body['content']['errorMsg'] ?? '';
        if (strpos($msg, '重复投保') !== false) {

            $this->repeat($msg);//重复投保
            if ($this->printer->repeatInsuredFlg) {
                $this->printer->success = false;
                $this->printer->repeatMessage = $msg;
                return $this;
            }
            $this->setError($msg);
            return $this;
        }

        $mainData = $body['content'] ?? [];
        if (isset($mainData['prpDvehicleInfoDto'])) {
            $this->setError('车型选择错误,请重新选择车辆编码为：' . ($mainData['prpDvehicleInfoDto']['vehicleId'] ?? '') . '的车型');
            return $this;
        }
        //车船税
        if ($carShipTax = $mainData['ciDto']['prpTcarShipTaxs'] ?? '') {
            $this->printer->carTaxPrinter->carShipTax = $carShipTax[0]['sumPayTax'] ?? '';
            $this->printer->carTaxPrinter->overdue = $carShipTax[0]['lateFee'] ?? '';
            $this->printer->carTaxPrinter->thisYearTax = $carShipTax[0]['taxDue'] ?? '';
        }

        $ciData = $mainData['ciDto'] ?? [];
        $biData = $mainData['biDto'] ?? [];
        if (!empty($biData)) {
            $biStartDate = $biData['startDate'] ?? '';
            $this->printer->biPremiumPrinter->biStartData = mktime($biData['startHour'] ?? '0', '0', '0', date('m', strtotime($biStartDate)), date('d', strtotime($biStartDate)), date('Y', strtotime($biStartDate)));
            $this->printer->biPremiumPrinter->biStartData = date('Y-m-d H:i:s', $this->printer->biPremiumPrinter->biStartData);
        }

        $lastPolicy = $biData['ciMainDto']['lastPolicys'] ?? '';
        $exDate = $lastPolicy[0]['lastPolicyExpireDate'] ?? '';
        $this->printer->premiumFactorPrinter->ComFactorAppend('上年商业险终保日期', 'lastBiEndData', $exDate);
        $this->printer->premiumFactorPrinter->ComFactorAppend('上年商业险起保日期', 'lastBiStartData', $lastPolicy[0]['lastPolicyEffectiveDate'] ?? '');
        //判断是否是商业险重复投保
        if ($exDate and $this->printer->biPremiumPrinter->biStartData and date('Y-m-d', strtotime($exDate)) > date('Y-m-d', strtotime($this->printer->biPremiumPrinter->biStartData))) {

            $this->printer->repeatInsurePrinter['biStartData'] = date('Y-m-d H:i:s', strtotime($exDate));
            $this->printer->repeatInsuredFlg = true;
            $this->printer->repeatMessage = '';
            $this->printer->success = false;
            return $this;
        }
        //交强险
        if (!empty($ciData)) {
            $this->printer->ciPremiumPrinter->ciPremium = $ciData['sumPremium'] ?? '';
            $this->printer->ciPremiumPrinter->ciDiscount = $ciData['finalRatio'] ?? '';
            $startDate = $ciData['startDate'] ?? '';
            $this->printer->ciPremiumPrinter->ciStartData = mktime($ciData['startHour'] ?? '0', '0', '0', date('m', strtotime($startDate)), date('d', strtotime($startDate)), date('Y', strtotime($startDate)));
            $this->printer->ciPremiumPrinter->ciStartData = date('Y-m-d H:i:s', $this->printer->ciPremiumPrinter->ciStartData);
            $endDate = $ciData['endDate'] ?? '';
            $this->printer->ciPremiumPrinter->ciEndData = mktime($ciData['endHour'] ?? '', '0', '0', date('m', strtotime($endDate)), date('d', strtotime($endDate)), date('Y', strtotime($endDate)));
            $this->printer->ciPremiumPrinter->ciEndData = date('Y-m-d H:i:s', $this->printer->ciPremiumPrinter->ciEndData);
            $this->printer->ciInquiryNo = $mainData['proposalNoCI'] ?? '';
            $ciFactor = $ciData['ciMainDto']['coverageInfos'] ?? [];
            $this->printer->premiumFactorPrinter->TCIFactorAppend('理赔调整系数', 'claimAdjustValue', $ciFactor['claimAdjustValue'] ?? '');
            $this->printer->premiumFactorPrinter->TCIFactorAppend('违法调整系数', 'peccancyAdjustValue', $ciFactor['peccancyAdjustValue'] ?? '');
            $this->printer->premiumFactorPrinter->TCIFactorAppend('交强险预期赔付率', 'billCTPELR', $ciData['prpTUndwrtCoefficients'][0]['billCTPELR'] ?? '');
            if (strlen($ciData['caRenewalType'] ?? '')) {
                $this->printer->premiumFactorPrinter->TCIFactorAppend('交强忠诚度', 'CIRenewalType', ['' => '', '0' => '新保', '1' => '续保', '2' => '转保'][$ciData['caRenewalType'] ?? '']);
            }
        }
        //商业险
        if (!empty($biData)) {
            $this->printer->biPremiumPrinter = new PremiumBIPrinter();
            $this->printer->biPremiumPrinter->biPremium = $biData['sumPremium'] ?? '';

            $biEndDate = $biData['endDate'] ?? '';
            $this->printer->biPremiumPrinter->biEndData = mktime($biData['endHour'] ?? '0', '0', '0', date('m', strtotime($biEndDate)), date('d', strtotime($biEndDate)), date('Y', strtotime($biEndDate)));
            $this->printer->biPremiumPrinter->biEndData = date('Y-m-d H:i:s', $this->printer->biPremiumPrinter->biEndData);
            $this->printer->biPremiumPrinter->biDiscount = $mainData['finalRatio'] ?? '';
            $this->printer->biInquiryNo = $mainData['proposalNoBI'] ?? '';
            $biFactor = $biData['ciMainDto']['riskItemInfos'] ?? [];
            //商业险系数
            $this->printer->premiumFactorPrinter->VCIFactorAppend('无赔优系数', 'ncdRate', $this->printer->ncdFactor);
            $this->printer->premiumFactorPrinter->VCIFactorAppend('无赔优原因', 'ncdCause', $mainData['profitCode']['ncdCause'] ?? '');
            $this->printer->premiumFactorPrinter->VCIFactorAppend('交通违法系数', 'ciLegalFactor', $biFactor['peccancyAdjustValue'] ?? '');
            $this->printer->premiumFactorPrinter->VCIFactorAppend('商业险预期赔付率', 'billCOMELR', $biData['prpTUndwrtCoefficients'][0]['billCOMELR'] ?? '');
            if (strlen($biData['caRenewalType'] ?? '')) {
                $this->printer->premiumFactorPrinter->VCIFactorAppend('商业忠诚度', 'BIRenewalType', ['' => '', '0' => '新保', '1' => '续保', '2' => '转保'][$biData['caRenewalType'] ?? '']);
            }
        }
        $this->printer->ncdFactor = $mainData['profitCode']['ncdRate'] ?? '0';

        $this->printer->premiumFactorPrinter->ComFactorAppend('自主定价系数', 'selfPricingCoef', $mainData['profitCode']['directSalesFlag'] ?? '0');
        $this->printer->premiumFactorPrinter->ComFactorAppend('整单预期赔付率', 'billELR', ($ciData['prpTUndwrtCoefficients'][0]['billELR'] ?? '') ?: ($biData['prpTUndwrtCoefficients'][0]['billELR'] ?? ''));

        $riskArr = $biData['prpTitemKinds'] ?? [];
        //非车
        if (isset($mainData['nonCarDto'])) {
            $this->printer->argc['channelOrderNo'] = $mainData['nonCarDto']['channelOrderNo'] ?? '';
            $this->printer->argc['nonCarChannelCode'] = $mainData['nonCarDto']['channelCode'] ?? '';

            $NCSinglePrinter = new NonCarInquirySinglePrinter();
            $NCSinglePrinter->inquiryNo = $mainData['nonCarDto']['proposalNo'] ?? '';
            $NCSinglePrinter->premium = $mainData['nonCarDto']['sumPremium'] ?? '';
            $NCSinglePrinter->amount = $mainData['nonCarDto']['sumAmount'] ?? '';
            $NCSinglePrinter->planCode = $mainData['nonCarDto']['insurancePlan'] ?? '';
            $NCSinglePrinter->statusCode = 'success';

            $this->printer->nonCarInquiryPrinter->noCarInquirySingleAppend($NCSinglePrinter);
            $this->printer->nonCarInquiryPrinter->totalPremium = $NCSinglePrinter->premium;
        }
        //险种
        foreach ($riskArr as $kind) {
            $coverage = new PremiumCoveragePrinter();
            $coverage->coverageCode = array_search(($kind['kindCode'] ?? ''), ZYICEnums::$coverageCode, true);
            $coverage->coverageName = IDockEnums::$coverageCode[$coverage->coverageCode] ?? '';
            $coverage->premium = $kind['premium'] ?? '';
            $coverage->basePremium = $kind['basePremium'] ?? '';
            $coverage->amount = $kind['amount'] ?? '';
            $coverage->discount = $kind['discount'] ?? '';
            if (in_array($coverage->coverageCode, ['C08001', 'C08002', 'C08003', 'C08004', 'C18001', 'C18002', 'C18003', 'C18004'])) {
                $coverage->serviceTimes = $kind['quantity'] ?? '0';
            }
            $this->printer->coverageListAppend($coverage);
        }
        //特约
        return $this;
    }

    /**
     * 重复投保
     * @param $msg
     */
    private function repeat($msg)
    {
        if (preg_match('/交强[[\s\S]*终保日期 ([\d\s:-]+)/', $msg, $matches)) {
            if ($matches[1] ?? '') {
                $ciStartData = date('Y-m-d H:i:s', strtotime($matches[1]));
                $this->printer->repeatInsurePrinter['ciStartData'] = $ciStartData;
                $this->printer->repeatInsuredFlg = true;
            }
        }

        if (preg_match('/商业[[\s\S]*终保日期 ([\d\s:-]+)/', $msg, $matches)) {
            if ($matches[1] ?? '') {
                $biStartData = date('Y-m-d H:i:s', strtotime($matches[1]));
                $this->printer->repeatInsurePrinter['biStartData'] = $biStartData;
                $this->printer->repeatInsuredFlg = true;
            }
        }

        if ($this->printer->repeatInsuredFlg) {
            $this->printer->repeatMessage = $msg;
            $this->printer->success = false;
        }
    }

    public function setNewEnergyCode()
    {
        $coverageList = $this->printer->coverageList;
        foreach ($coverageList as &$coverage) {
            /*** @var $coverage PremiumCoveragePrinter */
            $coverage->coverageCode = 'C1' . substr($coverage->coverageCode, '2', 4);
        }
    }

    public function setExt($mobile, $type)
    {
        $this->printer->argc['applicantMobile'] = $mobile;
        $this->printer->argc['relationType'] = $type;
    }

}
